import axios from "axios";
import store from "@/store";
import router from "@/router";
import iview from "view-design";
// export function getUserInfo(appId, time, signature, param) {
//   return req.post(
//     `https://oapi.dingtalk.com/sns/getuserinfo_bycode?accessKey=${appId}&timestamp=${time}&signature=${signature}`,
//     "获取用户信息",
//     param
//   );
// }

export function login(data) {
  return commonApi({
    method: "post",
    url: "/user/login",
    data,
    title: "用户登录",
    response: {},
  });
}

export function regisUser(data) {
  return commonApi({
    method: "post",
    url: "/user",
    data,
    title: "用户注册",
    response: {},
  });
}

export function log(data) {
  if (process.env.NODE_ENV === "development") {
    return;
  }
  return commonApi({
    method: "post",
    url: "/log",
    data,
    title: "添加日志",
    isLog: true,
    response: {},
  });
}

export function getResource() {
  return commonApi({
    method: "get",
    url: "/user/resource",
    title: "获取用户资源",
    response: {},
  });
}

export function createConfig(data) {
  return commonApi({
    method: "post",
    url: "/config/create",
    data,
    title: "创建配置",
    response: {},
  });
}

export function searchConfig(data) {
  return commonApi({
    method: "get",
    url: "/config/:key/:page/:pageSize",
    data,
    title: "查询配置",
    response: {},
  });
}

export function saveConfig(data) {
  return commonApi({
    method: "post",
    url: "/config",
    data,
    title: "新增/修改配置",
    response: {},
  });
}

export function deleteConfig(id) {
  return commonApi({
    method: "delete",
    url: "/config/:id",
    data: {
      id,
    },
    title: "删除配置",
    response: {},
  });
}

export function getConfig(key, value) {
  return commonApi({
    method: "get",
    url: "/config/:key/:value",
    data: {
      key,
      value,
    },
    title: "获取配置",
    response: {},
  });
}

export async function getDetail(id) {
  return commonApi({
    method: "get",
    url: "/interface/getDetailById/:id",
    data: {
      id,
    },
    title: "获取api详情",
    response: {},
  });
}

export async function getAllApis() {
  return commonApi({
    method: "get",
    url: "/interface/getAllApis",
    data: {},
    title: "获取api数据",
    response: {},
  });
}

export async function commonApi(info) {
  let { url, data, title, response, isLog } = info;
  if (!url || !info.method) {
    return;
  }
  let route = router.currentRoute;
  let baseURL = store.getters.appConfig.api;

  info.method = info.method.toLowerCase();
  info.baseURL = info.base_url ? info.base_url : baseURL;
  response = response ? response : {};
  let obj = pathParse(url, data);
  info.url = obj.path;
  info.data = obj.params;
  let token = localStorage.getItem("token");
  return new Promise((resolve) => {
    axios({
      ...info,
      headers: {
        ...info.headers,
        Authorization: "Bearer " + token,
      },
    })
      .then((res) => {
        if (res.status == 200) {
          let data = res.data;
          resolve(data);
          if (
            !isLog &&
            route.matched[0] &&
            route.matched[0].meta &&
            route.matched[0].meta.title
          ) {
            log({
              system: route.matched[0].meta.title,
              module: route.meta.title ? route.meta.title : route.name,
              type: "接口调用",
              info: `调用接口${title}成功`,
            });
          }
        } else {
          response.error = err ? err : true;
          handleRejected(err, route, title, isLog);
          resolve(response);
        }
      })
      .catch((err) => {
        response.error = err ? err : true;
        handleRejected(err, route, title, isLog);
        resolve(response);
      });
  });
}

function handleRejected(err, route, title, isLog) {
  if (
    !isLog &&
    route.matched[0] &&
    route.matched[0].meta &&
    route.matched[0].meta.title
  ) {
    log({
      system: route.matched[0].meta.title,
      module: route.meta.title ? route.meta.title : route.name,
      type: "接口调用",
      info: `调用接口${title}失败，错误原因${err.message.toString()}`,
    });
  }
  console.error(`${title}接口调用失败`);
  iview.Message.error(err.response.data.message);
}

function pathParse(path = "", params = {}) {
  let infoArr = path.split(":");
  let res;
  if (infoArr.length === 1) {
    res = path;
  } else {
    res = infoArr[0];
    infoArr.forEach((item, i) => {
      if (i) {
        let key = item.replace("/", "");
        res += params[key] ? params[key] : null;
        if (i < infoArr.length - 1) {
          res += "/";
        }
        delete params[key];
      }
    });
  }

  return { path: res, params };
}
